/**
 * 
 */
package common.quickvalid;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import common.quickvalid.validators.IValidator;
import common.utils.ClassUtils;

/**
 * 单个表单域的验证表达式解析器.
 * @author beansoft
 *
 */
public class FieldExpressionParser {
    private String fieldName;
    private String fieldDescription;
    private String validExpression;
    private static String VALIDATOR_PACKAGE = "common.quickvalid.validators";// 验证规则类所在包
    private static Map<String, IValidator> validators = new HashMap<String, IValidator>();
    static {
        try {
            //启动加载所有验证器 add by nassir wen 2012-07-18
            for (String fullName : ClassUtils.getClassNames(VALIDATOR_PACKAGE)) {
                String className = fullName.substring(fullName.lastIndexOf(".") + 1);
                //验证类都以小写开头
                if (firstIsLowercase(className)) {
                    IValidator validator = (IValidator) Class.forName(fullName).newInstance();
                    validators.put(className, validator);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    
    public FieldExpressionParser() {
    }
    /**
     * username,用户名,required min-length-5
     * @param expression
     */
    FieldExpressionParser(String expression) {
        String[] parts = expression.split(",");
        try {
            fieldName = parts[0];
            fieldDescription = parts[1];
            if (fieldDescription == null || fieldDescription.trim().length() == 0) {
                fieldDescription = fieldName;
            }
            validExpression = parts[2].trim();//避免额外的空格
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    String getFieldName() {
        return fieldName;
    }

    String getFieldDescription() {
        return fieldDescription;
    }

    /**
     * 分析验证器
     * @return
     */
    List<IValidator> getValidations() {
        List<IValidator> lists = new ArrayList<IValidator>();

        if (validExpression != null) {
            String[] parts = validExpression.split(" ");
            for (String part : parts) {
                String argsExpression = null;//规则表达式
                String className = null;// 规则类名
                String[] args = null;// 参数列表(可能为空)

                // 不带-号的简单规则, 一般是 required
                if (part.indexOf('-') == -1) {
                    className = part;
                } else // equals 需要单独处理
                {
                    if (part.indexOf("equals") != -1) {
                        className = "equals";
                        argsExpression = part.substring(className.length() + 1);
                    } else if (part.indexOf('-') > 0) {
                        part = part.replaceFirst("-", "_");// 类名转换为合法标识符: validate-ip ==> validate_ip

                        // 分析有参数的规则, 排除类名
                        if (part.indexOf('-') > 0) {
                            className = part.substring(0, part.indexOf('-'));//min_length-5-...更多参数
                            argsExpression = part.substring(className.length() + 1);
                        } else {
                            // 分析无参数的规则, 例如: validate-number, 没有参数
                            className = part;
                        }
                    }
                }

                if (argsExpression != null) {
                    args = argsExpression.split("-");
                }

                if (validators.containsKey(className)) {
                    IValidator validator = (IValidator) validators.get(className);
                    validator.setArgs(args);
                    validator.setExpression(argsExpression);// 原始表达式
                    lists.add(validator);
                } else {
                    System.err.println("验证器实现类" + VALIDATOR_PACKAGE + "." + className + "不存在!");
                }
            }
        }
        return lists;
    }

    /**
     * 是否小写字母开头
     * @param className
     * @return
     */
    private static boolean firstIsLowercase(String className) {
        if (className == null || className.length() == 0) {
            return false;
        }
        char startChar = className.charAt(0);
        if (startChar >= 'a' && startChar <= 'z') {
            return true;
        }
        return false;
    }
}
